<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>component-lifecycle-2</title>
</head>
<body>
  <!-- <div id="source" style="height:100px">
    输入的值：<input id="source" type="text" name="source" value="Bob" /> <br>
  </div> -->
  <div id="app"></div>
  <script type="text/javascript" src="../js/react.js"></script>
  <script type="text/javascript" src="../js/react-dom.js"></script>
  <script type="text/javascript">

    var logMixin = {
      _log: function(methodName, args) {
        console.log(this.name + ' :: ' + methodName, args);
      },
      componentWillUpdate: function() {
        this._log('componentWillUpdate', arguments);
      },
      componentDidUpdate: function() {
        this._log('componentDidUpdate', arguments);
      },
      componentWillMount: function() {
        this._log('componentWillMount', arguments);
      },
      componentDidMount: function() {
        this._log('componentDidMount', arguments);
      },
      componentWillUnmount: function() {
        this._log('componentWillUnmount', arguments);
      },
    };

    var counterComponent = React.createClass({
      name: "counter",
      // mixins: [logMixin],

      propTypes: {
        counter: React.PropTypes.number.isRequired,
      },
      // 校验状态是否一致，一致的话返回false，不必在重新渲染这个组件
      // 阻止不必要的更新，提高性能
      shouldComponentUpdate(nextProps, nextState) {
        return nextProps.counter !== this.props.counter;
      },
      render: function() {
        console.log(this.name + " :: render()");
        return React.DOM.span(null, this.props.counter);
      }
    });


    var myTextArea = React.createClass({
      name: 'TextAreaCounter',
      // mixins: [logMixin],

      propTypes: {
        defaultTexValue: React.PropTypes.string,
      },
      getDefaultProps: function() {
        return {
          defaultTextValue: '',
        }
      },
      getInitialState: function() {
        return {
          text: this.props.defaultTextValue,
        }
      },
      _textChange: function(ev) {
        this.setState({
          text: ev.target.value,
        })
      },
      render: function() {
        console.log(this.name + " :: render()");
        var counter = null;
        if(this.state.text.length > 0) {
          counter = React.DOM.h1(null,
            React.createElement(counterComponent, {
              counter: this.state.text.length,
            })
          );
        };

        return React.DOM.div(null,
          React.DOM.textarea({
            value: this.state.text,
            onChange: this._textChange,
          }),
          counter,
        );
      }
    });

    var myReactObj = ReactDOM.render(
      React.createElement(myTextArea,{
        defaultTextValue: 'Bob',
      }),
      document.getElementById("app")
    );
  </script>
</body>
</html>
